<template>
  <div class="monthly">
    <!-- 查询表单 -->
    <filter-form
      planType="month"
      showMonthPicker
      :showPushScreen="isAdmin"
      :onSubmit="handleSearch"
      :onClear="handleClear"
      :onExport="showExportDialog"
      :onPushScreen="handlePushScreen"
    />
    <div class="statistics">
      <div class="item" @click="showStaticsDialog">
        <i class="el-icon-user-solid"></i>
        已填报人数：
        <span class="num">{{importInfo.hasImport}}</span>
      </div>
      <div class="item" @click="showStaticsDialog">
        <i class="el-icon-user"></i>
        未填报人数：
        <span class="num">{{importInfo.noImport}}</span>
      </div>
    </div>
    <!-- 月报列表 -->
    <week-month-report-list
      v-loading.fullscreen="loading"
      element-loading-text="拼命加载中"
      element-loading-spinner="el-icon-loading"
      element-loading-background="rgba(0, 0, 0, 0)"
      planType="月"
      :loading="loading"
      :printing="printing"
      :weekRecords="weelyReportDatas"
      @onScrollLoad="handleScrollLoadData"
      @onReloadfetch="handleReLoadFetch"
    />
    <div v-if="noMore && weelyReportDatas.length" class="list-empty">没有更多了</div>
    <!-- 文件名输入对话框 -->
    <file-name-form-modal
      modalTitle="导出"
      :dialogVisible="dialogFileNameVisible"
      :onClose="() => { dialogFileNameVisible = false }"
      :onSubmit="handleExportAction"
    />
    <!-- 周报填报情况 -->
    <weekly-report-statisc-modal
      :reportData="importInfo"
      :dialogVisible="dialogReportStaticsVisible"
      :onClose="() => { dialogReportStaticsVisible = false }"
    />
  </div>
</template>

<script>
import { mapGetters } from "vuex";
import moment from 'moment'
import { parseTime, filterObj, dataURLtoFile } from "@/utils/index.js";
import { getWeekSchedule, pushWeekScheduleToScreen } from "@/api/plann.js";
import { htmlToPdf, uploadPdfFile } from '../utils/plan.js'

export default {
  computed: {
    ...mapGetters(["name", "id","roles"]),
    device() {
      return this.$store.state.app.device;
    },
    username() {
      return this.name && this.name.split("(")[0];
    },
    isAdmin() {
      return this.roles.some(role => ~role.indexOf('管理员'));
    },
  },
  components: {
    FilterForm: () => import("../components/FilterForm.vue"),
    WeekMonthReportList: () => import("../components/WeekMonthReportList.vue"),
    FileNameFormModal: () => import("../components/FileNameFormModal"),
    WeeklyReportStatiscModal: () => import('../components/WeeklyReportStatiscModal.vue')
  },
  data() {
    return {
      weelyReportDatas: [],
      loading: false,
      printing: false,
      filterParam: null,
      queryParam: {},
      pdfName: "周报",
      pdfOption: "toPdf",
      dialogFileNameVisible: false,
      dialogReportStaticsVisible: false,
      page: 1, // 滚动加载页码
      pageSize: 5, // 每页加载数量
      noMore: false, // 是否还有更多
      importInfo: {},
    };
  },
  mounted() {
    this.fetchWeeklyPlanList();
  },
  methods: {
    parseTime,
    showStaticsDialog() {
      // 只有管理员可以打开查看具体信息
      if(this.isAdmin) {
        this.dialogReportStaticsVisible = true
      }
    },
    showExportDialog() {
      if(!this.weelyReportDatas.length) {
        this.$message.warning('暂无数据可以导出')
        return
      }
      this.dialogFileNameVisible = true 
    },
     // 滚动加载数据
    handleScrollLoadData() {
      if(!this.noMore && !this.loading) {
        this.fetchWeeklyPlanList(this.filterParam)
      }
    },
    // 更新表格数据 刷新请求
    handleReLoadFetch() {
      this.clearScrollParam();
      this.fetchWeeklyPlanList(this.filterParam);
    },
    // 处理导出菜单操作
    async handleExportAction(name, type) {
      // 如果选择导出到word\excel
      if(type === 'toWord' || type === 'toExcel') {
        this.handleFetchExport(name, type)
      } else {
        // 如果选择导出到pdf
        if(!this.noMore) {
          this.clearScrollParam();
          await this.fetchWeeklyPlanList({...this.filterParam, page_size: 1000});
        }
        this.pdfOption = type;
        this.printing = true;
        this.dialogFileNameVisible =  false
        // 生成pdf
        setTimeout(() => {
          const pages = document.querySelector("#reportist").children;
          this.exportHTMLToPDF(pages, name);
        }, 600);
      }
    },
    // 请求后端 导出word文件
    async handleFetchExport(filename, type) {
      const typeUrl = {
        toWord: 'save_docx',
        toExcel: 'save_excel'
      }
      this.dialogFileNameVisible = false
      const { protocol, host } = window.location
      const params = filterObj({...this.queryParam, filename})
      const queryString = Object.keys(params).map(key => key + "=" + params[key]).join("&")
      window.open(`${protocol}//${host}/api/Work/week_workschedule/${typeUrl[type]}/?${queryString}`)
    },
    // 将html生成pdf
    async exportHTMLToPDF(pages, fileName) {
      const createMsg = this.$message({
        message: '正在生成pdf文件...',
        type: 'success',
        duration: 0
      });
      const worker = htmlToPdf(pages, fileName)
      // 如果发送到公告通知
      if (this.pdfOption === "toInfo") {
        worker
          .toPdf()
          .get("pdf")
          .then((pdf) => {
            var pdfData64 = pdf.output("datauristring"); //获取base64Pdf
            const pdfFile = dataURLtoFile(
              pdfData64,
              fileName + ".pdf"
            );
            createMsg.close()
            uploadPdfFile(pdfFile)
          });
      // 直接下载
      } else {
        await worker.save()
        this.printing = false;
        createMsg.close()
      }
    },
    // 处理推送周报到大屏
    async handlePushScreen() {
      if(!this.weelyReportDatas.length) return
      const { year , week_date } = this.weelyReportDatas[0]
      const param = {
        ...this.filterParam,
        type: '月',
        year,
        week_date,
        push_status: 'push'
      }
      const { data } = await pushWeekScheduleToScreen(param)
      if(data) {
        this.$message.success('推送至大屏成功！')
      }
    },
    // 点击查询
    handleSearch(param) {
      const { user, content, userType, monthRange, range_inspect, group } = param;
      const _param = {
        content,
        range_inspect
      };
      if (monthRange) {
        const [start, end] = monthRange;
        const startWeek = moment(start).format("YYYY-MM-DD");
        const endWeek = moment(end).format("YYYY-MM-DD");
        _param.date_start = startWeek
        _param.date_end = endWeek
      }
      // 当user为 u{id} 将u去除
      const _user = typeof user === "string" ? user.slice(1) : user;
      if (userType === "user") {
        _param.user = _user;
      } else {
        _param.department = _user;
      }
      if(group && group.length) {
        _param.group = group.join(',')
      }
      this.filterParam = _param
      this.clearScrollParam()
      this.fetchWeeklyPlanList(_param);
    },
    // 清除滚动查询参数
    clearScrollParam() {
      this.page = 1
      this.noMore = false
      this.weelyReportDatas = []
    },
    // 重置查询表单
    handleClear() {
      this.clearScrollParam()
      this.fetchWeeklyPlanList();
    },
    /**
     * 请求日历报告记录
     */
    async fetchWeeklyPlanList(filter = {}) {
      this.loading = true;
      const currentDay = moment()
      const startDate = currentDay.startOf('month').format("YYYY-MM-DD")
      const endDate = currentDay.endOf('month').format("YYYY-MM-DD")
     
      const param = {
        type: '月',
        page: this.page,
        date_start: startDate,
        date_end: endDate,
      };
      this.queryParam = {date_start: startDate, date_end: endDate, ...filter, type: "月" }

      try {
        const { data: result = {} } = await getWeekSchedule({ ...param, ...filter });
        const { data, import: hasImport, noimport: noImport, import_list, no_import_user_list } = result
        if(this.page == 1){
          this.importInfo = {hasImport, noImport, import_list, no_import_user_list}
        }
        this.weelyReportDatas = [...this.weelyReportDatas, ...data];
        if(!data.length || data.length < this.pageSize) {
          this.noMore = true
        }
        this.page++
        this.loading = false;
      } catch (error) {
        this.loading = false;
      }
    }
  }
};
</script>
<style lang="scss" scope>
.monthly {
  .list-empty {
    text-align: center;
    margin-bottom: 10px;
    color: #999;
  }
  .statistics {
    display: flex;
    align-items: center;
    justify-content: flex-end;
    padding-right: 45px;
    font-size: 14px;
    color: #666;
    padding: 10px 5px 10px 10px;
    margin: 0px auto -10px;
    width: 100%;
    max-width: 1200px;
    .item {
      cursor: pointer;
      margin-left: 20px;
      i {
        font-size: 18px;
      }
      .num {
        font-size: 16px;
        // font-weight: bold;
        color: #fb5b4a;
      }
    }
  }
}
</style>